<template>
  <div>
    <el-upload
      ref="uploadImageRef"
      action="imageUrl"
      list-type="picture-card"
      class="upload-img"
      :auto-upload="true"
      :http-request="uploadImg"
      :on-success="handleSuccess"
      :on-error="handleError"
      accept=".jpg,.jpeg,.png,.svg,.ico"
      :before-upload="beforeImageUpload"
      :limit="1"
      :file-list="imgs"
    >
      <div slot="trigger" class="upload-btn">
        <el-button size="small" type="primary">点击上传</el-button>
      </div>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file, 'uploadImageRef')"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>

      <span slot="tip">
        上传图片，最多上传1张图片。图片支持
        <em> jpg、jpeg、png、svg </em>格式，图片大小不超过 <em>5M</em> 。
      </span>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    value: String,
    imageUrl: String,
  },
  data() {
    return {
      addForm: "",
      disabled: false,
      dialogVisible: false,
      dialogImageUrl: "",
    };
  },
  computed: {
    imgs: function () {
      if (this.value) {
        let name = this.fileName;
        let url = "";
        if (/http/.test(this.value)) {
          url = this.value;
        } else {
          url = "http://b.xinyueai.com" + this.value;
        }
        if (!name) {
          name = this.value.replace(/.+\//, "");
          console.log(name);
        }
        console.log(url);
        return [{ name, url }];
      } else {
        return [];
      }
    },
  },
  methods: {
    uploadImg(e) {
      console.log(e);
      const fd = new FormData();
      console.log(e.file);
      fd.append("file", e.file);
      return this.$http.upload("/api/Common/UploadPhoto", fd);
      //   console.log(response);
      //   return response;
    },

    handleSuccess(response) {
      console.log(response);
      this.$emit("input", response.data.Data.picurl);
    },
    handleError(response) {
      console.error(response);
      this.$message.error("上传失败");
    },
    beforeImageUpload(file) {
      console.log(file);
      let typeName = file.name.substr(-4);
      let accept = ".jpg.jpeg.png.svg.ico";
      if (accept.indexOf(typeName) == -1) {
        this.$message.error("请上传文件 格式：.jpg.jpeg.png.svg");
        return false;
      }
      // const isJPG = file.type === "image/jpeg";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isLt5M) {
        this.$message.error("上传文件大小不能超过 5MB!");
        return false;
      }
      // return isJPG && isLt2M;
      return true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async handleDownload(file) {
      console.log(file);

      let { url, name } = file;
      this.$common.downloadFile({ url, name });
      // var canvas = document.createElement("canvas");
      // var img = document.createElement("img");
      // img.src = src;
      // img.onload = function () {
      //   canvas.width = img.width;
      //   canvas.height = img.height;
      //   var context = canvas.getContext("2d");
      //   context.drawImage(img, 0, 0, img.width, img.height);
      //   // window.navigator.msSaveBlob(canvas.msToBlob(),'image.jpg');
      //   // saveAs(imageDataUrl, '附件');
      //   canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
      //   canvas.toBlob((blob) => {
      //     let link = document.createElement("a");
      //     link.href = window.URL.createObjectURL(blob);
      //     link.download = "";
      //     link.click();
      //   }, "image/jpeg");
      //   // context.toBlob(function(blob) {
      //   // console.log('blob :', blob);

      //   // let link = document.createElement('a');
      //   // link.href = window.URL.createObjectURL(blob);
      //   // link.download = 'aaa';
      //   // }, "image/jpeg");
      // };
      // img.setAttribute("crossOrigin", "Anonymous");
    },
    handleRemove(file, name) {
      console.log(file);
      console.log(name);
      let arr = this.$refs[name].uploadFiles;
      let index = arr.indexOf(file);
      arr.splice(index, 1);
      // console.log(file, fileList);
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style lang="less" scoped>
.upload-img {
  display: flex;
  flex-direction: column-reverse;
  align-items: flex-start;
  .upload-btn {
    margin: 1rem;
    margin-left: 0;
  }
}
</style>
